﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microsoft.CSharp.RuntimeBinder;

namespace Prototipo.CMS.Infrastructure.Mvc
{
    public class PrototipoViewEngine : RazorViewEngine
    {
        public override ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
        {
            try
            {
                string themeName = controllerContext.Controller.ViewBag.Configuration.Theme.Name;
                
                var partialPath = string.Format("~/Themes/{0}/{1}.cshtml", themeName, partialViewName);

                if (!string.IsNullOrEmpty(partialPath))
                {
                    return new ViewEngineResult(this.CreatePartialView(controllerContext, partialPath), this);
                }
            }
            catch (Exception)
            {
                
            }
            return base.FindPartialView(controllerContext, partialViewName, useCache);
        }

        public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
        {
            try
            {
                string themeName = controllerContext.Controller.ViewBag.Configuration.Theme.Name;
                var viewPath = string.Format("~/Themes/{0}/{1}.cshtml", themeName, viewName);
                var masterPath = string.Format("~/Themes/{0}/Layout.cshtml", themeName);

                if (!(string.IsNullOrEmpty(viewPath)) &&
                    (masterPath != string.Empty || string.IsNullOrEmpty(masterName)))
                {
                    return new ViewEngineResult((this.CreateView(controllerContext, viewPath, masterPath)), this);
                }
            }

            catch (RuntimeBinderException ex)
            {

            }

            return base.FindView(controllerContext, viewName, masterName, useCache);
        }
    }
}
